package com.jxj.study.controller.Easypoi;

import com.alibaba.fastjson.JSONObject;
import com.jxj.study.domian.ExcelEntitys;
import com.jxj.study.domian.User;
import com.jxj.study.util.FileWithExcelUtil;
import com.jxj.study.util.ResponseModel;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/excel")
public class ExcelController {
    private static final Logger logger = LoggerFactory.getLogger(FileWithExcelUtil.class);

    @ResponseBody
    @RequestMapping("/json")
    public void jsonP(String json){
        HttpClient client = HttpClients.createDefault();
        // 要调用的接口方法
        String url = "http://localhost:" + 81 + "/map";
        HttpPost post = new HttpPost(url);
        HttpGet httpGet = new HttpGet();
        User user = new User();
        user.setAge(18);
        user.setName("username");
        try {
            StringEntity s = new StringEntity(JSONObject.toJSONString(user), "UTF-8");
            //s.setContentEncoding("UTF-8");//此处测试发现不能单独设置字符串实体的编码，否则出错！应该在创建对象时创建
            s.setContentType("application/json");
            post.setEntity(s);
            post.addHeader("content-type", "application/json;charset=UTF-8");
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回json格式：
                JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
                System.out.println("jsonObject  = "+jsonObject);
            }
        } catch (Exception e) {
            System.out.println("服务间接口调用出错！");
            e.printStackTrace();
            //throw new RuntimeException(e);
        }
    }

    @RequestMapping("/exportExcel/model")
    public void export(HttpServletResponse response){
        try {
            //模拟从数据库获取需要导出的数据
            List<ExcelEntitys> personList = new ArrayList<>();
            ExcelEntitys entitys = new ExcelEntitys();
            entitys.setEmail("10399@qq.com");
            entitys.setHouseholdAddress("四川");
            entitys.setIdentifyType("2");
            entitys.setIdcardAdress("广安");
            entitys.setIdentifyNo("511");
            entitys.setWorkAddress("成都");
            personList.add(entitys);
            FileWithExcelUtil.exportExcel(personList,"客户信息表","客户表",ExcelEntitys.class,"客户表.xls",response);
//            return ResponseModel.success("操作成功");
        } catch (Exception e) {
            logger.info("getCustomerPage", e);
//            return ResponseModel.fail("导出模版失败");
            // TODO: handle exception
        }

    }

    /**
     * 导入excel
     */
    @RequestMapping(value = "/importExcelForType", method = RequestMethod.POST)
    public ResponseModel importExcel(@RequestParam("file") MultipartFile file, String customerType) {
        try {
//          String filePath = "/Users/***/Downloads/response.xls";
            //解析excel，
//          List<CustomerList> personList = FileWithExcelUtil.importExcel(filePath, 1, 1, CustomerList.class);
            List<ExcelEntitys> personList = FileWithExcelUtil.importExcel(file, 1, 1, ExcelEntitys.class);
            //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
            System.out.println("导入数据一共【" + personList.size() + "】行");

            for (int i = 0; i < personList.size(); i++) {
                ExcelEntitys excel = personList.get(i);
            }
            logger.info(personList.toString());
            return ResponseModel.success("操作成功");

        } catch (Exception e) {
            // TODO: handle exception
            logger.error(e.toString());
            return ResponseModel.fail(e.getMessage());
        }
    }
}
